package com.hopedove.workshop.viewmodel

import android.text.Editable
import android.text.InputFilter
import android.text.TextWatcher
import android.widget.EditText
import android.widget.TextView
import androidx.databinding.ObservableBoolean
import androidx.databinding.ObservableField
import androidx.databinding.ObservableInt
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Transformations
import androidx.lifecycle.viewModelScope
import com.hadilq.liveevent.LiveEvent
import com.hopedove.data.Datetime
import com.hopedove.net.ApiCallResult
import com.hopedove.repository.CommonRepository
import com.hopedove.viewmodel.BaseViewModel
import com.hopedove.viewmodel.CommonEvent
import com.hopedove.workshop.api.*
import com.hopedove.workshop.data.pojo.ObservableRunningSituation
import com.hopedove.workshop.data.pojo.ObservableTakeInventoryItem
import com.hopedove.workshop.repository.WorkshopUserRepository
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch
import java.time.LocalDateTime
import java.time.format.DateTimeFormatter
import kotlin.math.log

class WorkshopTakeInventoryDetailViewModel (
    private val commonRepo: CommonRepository,
    private val userRepo: WorkshopUserRepository,
    private val api: WorkshopApi
) : BaseViewModel() {
    val title = ObservableField("纱支盘存明细")
    val username = ObservableField("")
    var currentMonth=LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM"))
    val date = ObservableField(currentMonth)
    //三连号
    val triplenumber = ObservableField("")
    //查询类型 1根据三联号查询，2 查询按钮，查询按钮 复选框默认不选中
    val queryType=ObservableField(1)

    private val _pickDate = LiveEvent<Datetime>()
    val pickDate: LiveData<Datetime> = _pickDate

    private val _takeInventoryList = LiveEvent<List<TakeInVentorySave>>()
    val takeInventoryList: LiveData<List<ObservableTakeInventoryItem>> =
        Transformations.map(_takeInventoryList) { list ->
            list.map {
                ObservableTakeInventoryItem(
                    it.id?:"",
                    it.clothtktNo ?:"",
                    it.clothNo?:"",
                    it.szqc?:"",
                    it.oriplace?:"",
                    ObservableField(it.cm1),
                    ObservableField(it.cm2),
                    ObservableField(it.cm3),
                    ObservableField(it.cm3_5),
                    ObservableField(it.cm4),
                    ObservableField(it.cm4_5),
                    ObservableField(it.cm5?:""),
                    ObservableField(it.cm5_5?:""),
                    ObservableField(it.cm6?:""),
                    ObservableField(it.cm6_5?:""),
                    ObservableField(it.cm7?:""),
                    ObservableField(it.cm7_5?:""),
                    ObservableField(it.cm8?:""),
                    ObservableField(it.cm8_5?:""),
                    ObservableField(it.onMachine?:""),
                    it.isimport?:"",
                    it.yarn_class?:"" ,
                  it.yllx?:"",
                   it.ylwz?:"",
                    if(it.state=="0") true else false,
                    ObservableBoolean(if(queryType.get()==1) true else false),
                )
            }
        }

    val noListData: LiveData<Boolean> =
        Transformations.map(takeInventoryList) { it == null || it.isEmpty() }

    private var confirmJob: Job? = null
    private var deleteJob: Job? = null
    private var queryJob: Job? = null


    override fun load() = viewModelScope.launch {
        userRepo.getSignedInUserName()?.let { username.set("记录人：$it") }
        getMonth()
    }

    /**
     * 三联号，回车
     */
    fun onMachineNoActionDone() {
        val triplenumber = triplenumber.get()!!
        if (triplenumber.isEmpty()) return

        // 清空列表
        _takeInventoryList.value=emptyList()
        queryType.set(1)
        queryTakeInventoryBatchList()
    }
    // 点击选择日期控件
    fun onPickDateClick() {
        _pickDate.value = Datetime.parseEnMonthFormat(date.get())
    }

    // 更新日期
    fun updateDate(datetime: Datetime) {
        date.set(datetime.dateFormatMonth())
    }
    // 点击确认
    fun onConfirmClick() {
        confirmList()
    }
    // 点击查询
    fun onQueryClick() {
        queryType.set(2)
        queryTakeInventoryBatchList()
    }

    // 点击删除
    fun onDeleteClick() {
        deleteList()
    }
    //查询接口
    private  fun queryTakeInventoryBatchList(){
        if(queryType.get()==1&&triplenumber.get().equals("")){//查询接口 三联号可为空
            _toastText.value = "请输入三联号"
            return
        }

        val userSession = userRepo.getSignedUserSession()!!

        if (queryJob?.isCompleted?.not() == true) return

        queryJob = viewModelScope.launch {
            _loading.value = true
            when (val result =
                api.querytakeInventoryList(
                    userSession.userId,
                    date.get(),
                    triplenumber.get()?:"",
                    queryType.get()?:1
                )) {
                is ApiCallResult.Success -> {
                    _takeInventoryList.value = result.data!!
                }
                is ApiCallResult.Error -> {
                    _toastText.value = result.message!!
                }
            }
            _loading.value = false
        }
    }
    //保存
    private fun confirmList() {
        takeInventoryList.value ?: return
        if (takeInventoryList.value!!.none { it.op.get() }) {
            _toastText.value = "请勾选保存条目"
            return
        }

        val userSession = userRepo.getSignedUserSession() ?: return

        if (confirmJob?.isCompleted?.not() == true) return

        confirmJob = viewModelScope.launch {
            _loading.value = true
            val remaining = mutableListOf<ObservableTakeInventoryItem>()
            val confirm = mutableListOf<ObservableTakeInventoryItem>()
            takeInventoryList.value!!.forEach { item ->
                if (item.op.get()) {
                    confirm.add(item)
                } else {
                    remaining.add(item)
                }
            }

            val savingList = confirm.map {
                TakeInVentorySave(
                    it.id,
                    it.clothtktNo,
                    it.clothNo,
                    it.szqc,
                    it.oriplace,
                    it.cm1.get() ?:"",
                    it.cm2.get() ?:"",
                    it.cm3.get() ?:"",
                    it.cm3_5.get() ?:"",
                    it.cm4.get() ?:"",
                    it.cm4_5.get() ?:"",
                    it.cm5.get() ?:"",
                    it.cm5_5.get() ?:"",
                    it.cm6.get() ?:"",
                    it.cm6_5.get() ?:"",
                    it.cm7.get() ?:"",
                    it.cm7_5.get() ?:"",
                    it.cm8.get() ?:"",
                    it.cm8_5.get() ?:"",
                    it.onMachine.get() ?:"",
                    it.isimport?:"",
                    it.yarn_class?:"" ,
                    it.yllx?:"",
                    it.ylwz?:"",
                    if(it.state==true) "0" else "1",
                    date.get()?:currentMonth

                )
            }

            when (val result =
                api.saveTakeInventory(userSession.userId, userSession.userName, savingList)) {
                is ApiCallResult.Success -> {
                    _toastText.value = "保存成功"
                    triplenumber.set("")
                    //保存成功之后再查询
                    queryType.set(2)
                    queryTakeInventoryBatchList()
                }

                is ApiCallResult.Error -> {
                    _toastText.value = result.error
                }

            }
            _loading.value = false
        }
    }

    private fun deleteList() {
         takeInventoryList.value ?: return

        if (takeInventoryList.value!!.none { it.op.get() }) {
            _toastText.value = "请勾选删除的条目"
            return
        }

        val userSession = userRepo.getSignedUserSession() ?: return

        if (deleteJob?.isCompleted?.not() == true) return


        deleteJob = viewModelScope.launch {
            _loading.value = true
            val remaining = mutableListOf<ObservableTakeInventoryItem>()
            val delete = mutableListOf<ObservableTakeInventoryItem>()
            takeInventoryList.value!!.forEach { item ->
                if (item.op.get()) {
                    delete.add(item)
                } else {
                    remaining.add(item)
                }
            }
            val deleteList = delete.map {
                TakeInVentorySave(
                    it.id,
                    it.clothtktNo,
                    it.clothNo,
                    it.szqc,
                    it.oriplace,
                    it.cm1.get() ?:"",
                    it.cm2.get() ?:"",
                    it.cm3.get() ?:"",
                    it.cm3_5.get() ?:"",
                    it.cm4.get() ?:"",
                    it.cm4_5.get() ?:"",
                    it.cm5.get() ?:"",
                    it.cm5_5.get() ?:"",
                    it.cm6.get() ?:"",
                    it.cm6_5.get() ?:"",
                    it.cm7.get() ?:"",
                    it.cm7_5.get() ?:"",
                    it.cm8.get() ?:"",
                    it.cm8_5.get() ?:"",
                    it.onMachine.get() ?:"",
                    it.isimport?:"",
                    it.yarn_class?:"" ,
                    it.yllx?:"",
                    it.ylwz?:"",
                    if(it.state==true) "0" else "1",
                    date.get()?:currentMonth
                )
            }

            when (val result =
                api.deleteTakeInventory(userSession.userId, userSession.userName, deleteList)) {

                is ApiCallResult.Success -> {
                    _toastText.value = "删除成功"
                    val remaindList = remaining.map {
                        TakeInVentorySave(
                            it.id,
                            it.clothtktNo,
                            it.clothNo,
                            it.szqc,
                            it.oriplace,
                            it.cm1.get() ?:"",
                            it.cm2.get() ?:"",
                            it.cm3.get() ?:"",
                            it.cm3_5.get() ?:"",
                            it.cm4.get() ?:"",
                            it.cm4_5.get() ?:"",
                            it.cm5.get() ?:"",
                            it.cm5_5.get() ?:"",
                            it.cm6.get() ?:"",
                            it.cm6_5.get() ?:"",
                            it.cm7.get() ?:"",
                            it.cm7_5.get() ?:"",
                            it.cm8.get() ?:"",
                            it.cm8_5.get() ?:"",
                            it.onMachine.get() ?:"",
                            it.isimport?:"",
                            it.yarn_class?:"" ,
                            it.yllx?:"",
                            it.ylwz?:"",
                            if(it.state==true) "0" else "1",
                            date.get()?:currentMonth
                        )
                    }
                    // 刷新列表
                    _takeInventoryList.value = remaindList!!
                }

                is ApiCallResult.Error -> {
                    _toastText.value = result.error
                }

            }
            _loading.value = false
        }

      }


    private suspend fun getMonth() {
            when (val result =
                api.getTakeInventoryMonth()) {
                is ApiCallResult.Success -> {
                    if(!result.data.isNullOrEmpty()&&!result.data.equals("null")){
                        date.set(result.data)
                    }

                }
            }
    }


}